package com.zzl.study.demo.controller;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * 基本的聊天Controller
 *
 * @author: zhangzl
 * @date: 2025/9/29 10:06
 * @version: 1.0
 */
@RestController
@RequestMapping("/basic-chat")
public class BasicChatController {

    /**
     * 默认提示语
     */
    private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手，请根据用户提问回答！";

    /**
     * 聊天客户端
     */
    private final ChatClient dashScopeChatClient;

    /**
     * 构造函数
     *
     * @param chatClientBuilder ChatClient 构造器
     */
    public BasicChatController(ChatClient.Builder chatClientBuilder) {
        DashScopeChatOptions chatOptions = DashScopeChatOptions.builder().withTopP(0.7).build();
        this.dashScopeChatClient = chatClientBuilder
                .defaultSystem(DEFAULT_PROMPT)
                // 实现 Logger 的 Advisor
                .defaultAdvisors(new SimpleLoggerAdvisor())
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(chatOptions)
                .build();
    }

    /**
     * ChatClient 简单调用
     *
     * @param query 查询
     * @return 结果
     */
    @GetMapping("/simple")
    public String simpleChat(@RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？") String query, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        return this.dashScopeChatClient.prompt(query).call().content();
    }

    /**
     * ChatClient 流式调用
     * http请求头：Accept: text/event-stream
     *
     * @param query 查询
     * @return 响应流
     */
    @GetMapping("/stream")
    public Flux<String> streamChat(@RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？") String query, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        return this.dashScopeChatClient.prompt(query).stream().content();
    }

}
